package com.hw.controller;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hw.pojo.EsStand;
import com.hw.service.StandService;
import com.hw.util.R;
import com.hw.vo.StandVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 国兴越
 * @version 1.0
 * Create by
 */
@RestController
@RequestMapping("stand")
public class StandController {


    @Autowired
    StandService standService;

    @Autowired
    OSS oss;


    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;


    /**
    * //TODO 创建索引
    * @author 国兴越
    * @date 2024/3/12 12:29
 * @return com.hw.util.R
    */

    @PostMapping("/create")
    public R create(){

        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsStand.class);

        indexOps.create();

        Document mapping = indexOps.createMapping();
        indexOps.putMapping(mapping);

        return R.ok().message("索引创建完成");
    }


    /**
    * //TODO 图片+视频上传
    * @author 国兴越
    * @date 2024/3/12 12:29
 * @param file
 * @param type
 * @return com.hw.util.R
    */

    @PostMapping("upload/{type}")
    private R upload(@RequestBody MultipartFile file, @PathVariable Integer type){

        String filename = file.getOriginalFilename();

        String suffix = filename.substring(filename.lastIndexOf(".") + 1);


        if(type==1){
            if(!(suffix.equals("jpg")||suffix.equals("png"))){
                return R.error().message("文件格式错误");
            }
        }
        if(type==2){
            if(!(suffix.equals("mp4")||suffix.equals("avi"))){
                return R.error().message("视频格式错误");
            }
        }

        String fileName= UUID.randomUUID().toString()+"."+suffix;

        try {
            oss.putObject("2108-gxy",fileName,file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return R.ok().message("文件上传成功").data("fullPath","https://2108-gxy.oss-cn-beijing.aliyuncs.com/"+fileName);

    }


    /**
    * //TODO  列表
    * @author 国兴越
    * @date 2024/3/12 12:28
 * @param standVo
 * @return com.hw.util.R
    */



    @PostMapping("/list")
    public R list(@RequestBody StandVo standVo){

         return standService.lists(standVo);

    }


    @PostMapping("/save")
    public R save(@RequestBody StandVo standVo){


        return standService.add(standVo);

    }




}
